package com.example.administrator.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.administrator.myapplication.bean.ScoreBean;
import com.example.administrator.myapplication.biz.ScoreBiz;
import com.example.administrator.myapplication.util.ToastUtil;

public class WinActivity extends Activity implements View.OnClickListener{
    private EditText mEditText;
    private Button mButton;
    private ScoreBiz mScoreBiz;
    private int mLevel;
    private long mScore;
    private String mName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_win);
        mEditText = (EditText) findViewById(R.id.et_name);
        mEditText.setText(load());
        mButton = (Button) findViewById(R.id.bt_commit);
        mButton.setOnClickListener(this);

        mScoreBiz = new ScoreBiz(this);
        //得到数据
        Intent intent = getIntent();
        mLevel = intent.getIntExtra("level", 3);
        mScore = intent.getLongExtra("time", 0);
    }

    @Override
    public void onClick(View v) {
        //得到输入的名字
        mName = mEditText.getText().toString();
        if(TextUtils.isEmpty(mName)){
            ToastUtil.show(this,"名字不能为空");
            return;
        }
        ScoreBean bean = new ScoreBean(mLevel,mScore,mName);
        long id = mScoreBiz.insert(bean);
        if(id == -1){
            ToastUtil.show(this,"数据库错误");
        }
        else {
            ToastUtil.show(this,"添加成功！");
        }
        save(mName);
        this.finish();
    }
    //保存用户偏好设置
    private void save(String name){
        SharedPreferences sharedPref = this.getSharedPreferences("savename",MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("name",name);
        editor.commit();
    }
    private String load(){
        SharedPreferences sharePref = this.getSharedPreferences("savename",MODE_PRIVATE);
        return sharePref.getString("name",null);
    }
}
